package com.voicechat.firstmet.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.voicechat.firstmet.App;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PayResult;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.AlipaySerivice;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.CircleImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: BuyVIPActivity
 * @Description: 购买vip activity_imessage
 * @Author: ljp
 * @CreateDate: 2018/10/8 20:10
 * @Version: 1.0
 */
public class BuyVIPActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_buy)
    TextView tvBuy;
    @BindView(R.id.image_icon)
    CircleImageView imageIcon;
    @BindView(R.id.tv_nik_name)
    TextView tvNikName;
    @BindView(R.id.linear_member)
    LinearLayout linearMember;
    @BindView(R.id.tv_vip_state)
    TextView tvVipState;
    @BindView(R.id.tv_1_month)
    TextView tv1Month;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_18_money)
    TextView tv18Money;
    @BindView(R.id.rela_vip_1)
    RelativeLayout relaVip1;
    @BindView(R.id.tv_3_month)
    TextView tv3Month;
    @BindView(R.id.tv_money_3)
    TextView tvMoney3;
    @BindView(R.id.tv_50_money)
    TextView tv50Money;
    @BindView(R.id.tv_3_month_original_cost)
    TextView tv3MonthOriginalCost;
    @BindView(R.id.rela_vip_3)
    RelativeLayout relaVip3;
    @BindView(R.id.tv_12_month)
    TextView tv12Month;
    @BindView(R.id.tv_money_168)
    TextView tvMoney168;
    @BindView(R.id.tv_168_money)
    TextView tv168Money;
    @BindView(R.id.tv_12_month_original_cost)
    TextView tv12MonthOriginalCost;
    @BindView(R.id.rela_vip_12)
    RelativeLayout relaVip12;
    @BindView(R.id.radio_buy_zhifubao)
    RadioButton radioBuyZhifubao;
    @BindView(R.id.linear_buy_zhifubao)
    LinearLayout linearBuyZhifubao;
    @BindView(R.id.radio_buy_weixin)
    RadioButton radioBuyWeixin;
    @BindView(R.id.linear_buy_weixin)
    LinearLayout linearBuyWeixin;
    @BindView(R.id.et_give_id)
    EditText etGiveId;
    @BindView(R.id.tv_money_sum)
    TextView tvMoneySum;
    @BindView(R.id.radio_vip_renew)
    CheckBox radioVipRenew;
    @BindView(R.id.radio_group)
    RelativeLayout radioGroup;
    @BindView(R.id.tv_alipay)
    TextView tvAlipay;
    @BindView(R.id.tv_1_month_original_cost)
    TextView tv1MonthOriginalCost;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String token;
    private String id;
    private String deviceInfo;
    private String data;
    private String payWay;//支付方式
    private String monthPay;//购买会员月份
    private String moneyGold;//购买会员金额
    private String TAG = "BuyVIPActivity";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_buy_vip;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        try {
                            JSONObject jsonObject = new JSONObject(resultInfo);
                            if (jsonObject.has("alipay_trade_app_pay_response")) {
                                JSONObject alipay_trade_app_pay_response = jsonObject.getJSONObject("alipay_trade_app_pay_response");
                                if (alipay_trade_app_pay_response.has("out_trade_no")) {
                                    String out_trade_no = alipay_trade_app_pay_response.getString("out_trade_no");
                                    judeRecharge(out_trade_no);//判断是否充值成功
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        toast_MakeText("支付已经取消");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showPopu();//弹出充值失败框
                    }
                    break;
                }
            }
        }
    };

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        id = mySeleInfo.getId();
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        Log.i(TAG, "initLayout: ------data----" + data);
        data = getIntent().getStringExtra("data");
        initView();
    }

    /**
     * @return
     * @method
     * @description 购买会员失败
     * @date: 2018/11/6 18:03
     * @author: ljp
     */
    private void showPopu() {
        View view = View.inflate(context, R.layout.popi_pay_fail, null);
        PopUtils.showPopupWindow(activity, view, false);
        LinearLayout imageView = view.findViewById(R.id.image_close);
        TextView tvSure = view.findViewById(R.id.tv_sure);
        ImageView icon = view.findViewById(R.id.image_icon);
        TextView text = view.findViewById(R.id.tv_text);
        icon.setImageResource(R.mipmap.vip_faild);
        text.setText("购买失败");
        tvSure.setText("重新购买");
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PopUtils.isPopShowing()) {
                    PopUtils.hidePopupWindow();
                }
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PopUtils.isPopShowing()) {
                    PopUtils.hidePopupWindow();
                }
            }
        });

    }

    /**
     * @return
     * @method
     * @description 结果的判断
     * @date: 2019/1/10 10:09
     * @author: ljp
     */
    private void judeRecharge(String orderString) {
        AlipaySerivice.judeAlipayRechargeVIP(orderString).subscribe(result -> {
            Log.i(TAG, "judeRecharge: -----" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                Intent intent = new Intent(activity, AllSuccessActivity.class);
                intent.putExtra("flag", "4");
                startActivity(intent);
                removeActivity();
                finish();
            } else {
                toast_MakeText(result.getMsg());
                showPopu();//弹出充值失败框
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
            showPopu();//弹出充值失败框
            Log.i(TAG, "judeRecharge: ---------" + throwable.toString());
        });
    }

    private void initView() {
        GlideLoadUtils.getInstance().glideLoad(App.getContext(), OssConfig.OSS_HTTP
                + mySeleInfo.getAvatarUrl(), imageIcon);
        tvVipState.setText(data);
        //画线效果
        tv1MonthOriginalCost.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        tv3MonthOriginalCost.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        tv12MonthOriginalCost.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

        tvNikName.setText(mySeleInfo.getNickName());
        payWay = "Alipay";
        setLayoutCacalBg(relaVip1, tv1Month, tvMoney, tv18Money);
    }

    @OnClick({R.id.linear_back, R.id.tv_buy, R.id.linear_buy_zhifubao, R.id.linear_buy_weixin
            , R.id.rela_vip_1, R.id.rela_vip_3, R.id.rela_vip_12, R.id.tv_alipay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back://返回
                context.startActivity(new Intent(context, MemberCenterActivity.class));
                finish();
                break;
            case R.id.tv_buy://购买记录
                startActivity(new Intent(activity, BuyVipRecordActivity.class));
                break;
            case R.id.linear_buy_zhifubao://支付宝
                setWay(view);
                break;
            case R.id.linear_buy_weixin://微信
                setWay(view);
                break;
            case R.id.rela_vip_1:
                setLayoutCacalBg(relaVip1, tv1Month, tvMoney, tv18Money);
                break;
            case R.id.rela_vip_3:
                setLayoutCacalBg(relaVip3, tv3Month, tvMoney3, tv50Money);
                break;
            case R.id.rela_vip_12:
                setLayoutCacalBg(relaVip12, tv12Month, tvMoney168, tv168Money);
                break;
            case R.id.tv_alipay://去支付
                toPay();
                break;
        }
    }

    /**
     * @return
     * @method
     * @description 去支付
     * @date: 2019/1/8 11:30
     * @author: ljp
     */
    private void toPay() {
        String number = null;
        String trim = etGiveId.getText().toString().trim();
        if (!TextUtils.isEmpty(trim)) {
            if (trim.length() < 8) {
                toast_MakeText("请输入8位数的id");
                return;
            } else {
                number = etGiveId.getText().toString().trim();
            }
        } else {
            number = mySeleInfo.getNumber();
        }
        if (payWay.equals("Alipay")) {//支付宝支付
            // Log.i(TAG, "toPay: ----------"+monthPay+","+moneyGold);
            // Log.i(TAG, "toPay: -------number---"+number);
            AlipaySerivice.alipayRechargeVIP(number, moneyGold + "," + monthPay).subscribe(alipayBean -> {
                // Log.i(TAG, "toPay: ---------"+alipayBean.getMap().getOrderStr().toString());
                if (alipayBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    setAlipay(alipayBean.getMap().getOrderStr());
                } else if (alipayBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                    Utils.setToken(context);
                } else {
                    toast_MakeText(alipayBean.getMsg());
                }
            }, throwable -> {
                toast_MakeText(getResources().getString(R.string.net_error));
                Log.i(TAG, "toPay: ---------" + throwable.toString());
            });
        } else {

        }
    }

    /**
     * @return
     * @method
     * @description 支付宝支付
     * @date: 2019/1/10 10:44
     * @author: ljp
     */
    private void setAlipay(String orderInfo) {
        final Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i(TAG, "run: -----------" + result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * @return
     * @method
     * @description 改变选定布局背景和字体颜色
     * @date: 2018/10/9 19:57
     * @author: ljp
     */
    private void setLayoutBg(RelativeLayout rela, TextView tvMonth, TextView tvmoney, TextView tvmoneySum) {
        rela.setSelected(true);
        tvMonth.setTextColor(getResources().getColor(R.color.colorC9A874));
        tvmoney.setTextColor(getResources().getColor(R.color.color9C7C4A));
        tvmoneySum.setTextColor(getResources().getColor(R.color.color9C7C4A));
        String money = tvmoneySum.getText().toString();
        this.monthPay = tvMonth.getText().toString().substring(0, tvMonth.getText().toString().length() - 2);
       /* if (monthPay.equals("3")) {
            monthPay = "4";
        } else if (monthPay.equals("12")) {
            monthPay = "18";
        }*/
        this.moneyGold = money.substring(0, money.length() - 3);
        this.tvMoneySum.setText("￥" + money);
    }
    /**
     * @return
     * @method
     * @description 改变未选定布局背景和字体颜色
     * @date: 2018/10/9 19:57
     * @author: ljp
     */
    private void setLayoutUnseBg(RelativeLayout rela, TextView tvMonth, TextView tvmoney, TextView tvmoneySum) {
        rela.setSelected(false);
        tvMonth.setTextColor(getResources().getColor(R.color.color666666));
        tvmoney.setTextColor(getResources().getColor(R.color.colorC9A874));
        tvmoneySum.setTextColor(getResources().getColor(R.color.colorC9A874));
    }

    private void setLayoutCacalBg(RelativeLayout rela, TextView tvMonth, TextView tvmoney, TextView tvmoneySum) {
        if (rela == relaVip1) {
            setLayoutUnseBg(relaVip3, tv3Month, tvMoney3, tv50Money);
            setLayoutUnseBg(relaVip12, tv12Month, tvMoney168, tv168Money);
            setLayoutBg(rela, tvMonth, tvmoney, tvmoneySum);
        } else if (rela == relaVip3) {
            setLayoutUnseBg(relaVip1, tv1Month, tvMoney, tv18Money);
            setLayoutUnseBg(relaVip12, tv12Month, tvMoney168, tv168Money);
            setLayoutBg(rela, tvMonth, tvmoney, tvmoneySum);
        } else if (rela == relaVip12) {
            setLayoutUnseBg(relaVip1, tv1Month, tvMoney, tv18Money);
            setLayoutUnseBg(relaVip3, tv3Month, tvMoney3, tv50Money);
            setLayoutBg(rela, tvMonth, tvmoney, tvmoneySum);
        }
    }

    /**
     * @return
     * @method
     * @description radioButton支付方式的判断
     * @date: 2018/10/10 10:14
     * @author: ljp
     */
    private void setWay(View radioButton) {
        if (radioButton == linearBuyZhifubao) {
            payWay = "Alipay";
            radioBuyZhifubao.setChecked(true);
            radioBuyWeixin.setChecked(false);
        } else if (radioButton == linearBuyWeixin) {
            payWay = "WeChatPay";
            radioBuyZhifubao.setChecked(false);
            radioBuyWeixin.setChecked(true);
        }
    }

    @Override
    public void onBackPressed() {
        context.startActivity(new Intent(context, MemberCenterActivity.class));
        finish();
    }
}
